import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/manager/xindong_notice_ctr.dart';
import 'package:xindong/manager/xindong_permission_ctr.dart';
import 'package:xindong/routes/account/xindong_login_yemian.dart';
import 'package:xindong/routes/tab_bar/xindong_tab_bar_yemian.dart';
import 'package:xindong/widgets/xindong_loading.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

import 'common/xindong_all.dart';
import 'common/xindong_methods.dart';
import 'manager/xindong_reset_singleton.dart';
import 'manager/xindong_user_controller.dart';

class XinDongMainYeMian extends StatefulWidget {
  const XinDongMainYeMian({Key? key}) : super(key: key);

  @override
  State<XinDongMainYeMian> createState() => _XinDongMainYeMianState();
}

class _XinDongMainYeMianState extends State<XinDongMainYeMian> with WidgetsBindingObserver {
  DateTime? _lastPressedAt = DateTime.now();
  bool _launchCompleted = true;
  bool _isActive = true;

  // 定时轮询 每5秒调一次
  Timer? _applicationTimer;

  @override
  void initState() {
    super.initState();
    _lastPressedAt = DateTime.now();
    WidgetsBinding.instance.addObserver(this); //添加观察者
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      // 每日重置（登录成功到TabBar调用，每次到前台调用）
      XinDongDailyResetSingleton.instance.setup();

      // 定时器
      createTimer();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); //移除观察者
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop(),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: GetBuilder<XinDongUserController>(
          id: "loginStatus",
          builder: (userController) => _launchYeMian(userController),
        ),
      ),
    );
  }

  Future<bool> Function()? _onWillPop() {
    if (Platform.isIOS) {
      return null;
    }
    return () async {
      if (_lastPressedAt == null || DateTime.now().difference(_lastPressedAt!) > const Duration(seconds: 2)) {
        showToast("再按一次退出应用", milliseconds: 1000);
        _lastPressedAt = DateTime.now();
        return Future.value(false);
      } else {
        // 退出app
        _lastPressedAt = DateTime.now();
        return Future.value(true);
      }
    };
  }

  Widget _launchYeMian(XinDongUserController userController) {
    mDebugPrint("登录状态：${userController.isUserCompleted}");
    // 登录
    if (userController.isUserCompleted == false) {
      return const XinDongLoginYeMian();
    } else {
      if (_launchCompleted == false) {
        // 加载中，登录中
        return const XinDongLoadingCenter();
      } else {
        // 首页
        return const XinDongTabBarYeMian();
      }
    }
  }

  /// 定时获取消息
  Future<void> createTimer() async {
    final seconds = XinDongAll.instance.isRelease ? 5 : 60;
    _applicationTimer?.cancel();
    _applicationTimer = null;
    _applicationTimer = Timer.periodic(Duration(seconds: seconds), (timer) async {
      // 不在前台
      if (_isActive == false) {
        return;
      }
      // 未登录
      if (XinDongUserController.to.isUserCompleted == false) {
        return;
      }
      // 消息轮询
      XinDongNoticeCtr.to.messageUnreadCount();
    });
  }

  /// 应用生命周期状态监听
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.inactive:
        {
          // 应用程序处于闲置状态-挂起悬浮小卡片
          Future.delayed(const Duration(milliseconds: 100)).whenComplete(() {
            // 暂停所有播放器播放
            XinDongAll.instance.pauseAllPlayer();
          });
        }
        break;
      case AppLifecycleState.paused:
        {
          _isActive = false;
          // 应用程序暂停活跃-后台
          Future.delayed(const Duration(milliseconds: 100)).whenComplete(() async {
            try {
              XinDongAll.instance.applicationActive = false;

              // 暂停所有播放器播放
              XinDongAll.instance.pauseAllPlayer();

              if (Platform.isAndroid) {
                // 后台时能够收到离线消息
                TencentImSDKPlugin.v2TIMManager.getOfflinePushManager().doBackground(unreadCount: 0);
              }
            } catch (error) {
              mCatchPrint(error);
            }
          });
        }

        break;
      case AppLifecycleState.resumed:
        {
          _isActive = true;
          // 应用程序恢复活跃-前台。
          Future.delayed(const Duration(milliseconds: 100)).whenComplete(() async {
            if (Platform.isAndroid) {
              // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
              TencentImSDKPlugin.v2TIMManager.getOfflinePushManager().doForeground();
            }
            XinDongAll.instance.applicationActive = true;

            // 每日重置（登录成功到TabBar调用，每次到前台调用）
            XinDongDailyResetSingleton.instance.setup();

            // 权限
            XinDongPermissionCtr.to.setup();
          });
        }

        break;

      case AppLifecycleState.detached:
        // 当前页面即将退出
        break;
      case AppLifecycleState.hidden:
        break;
    }
  }
}
